package com.xiaoying.server.publish.task;

import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xiaoying.server.publish.comomon.upyun.UpYunUtil;
import com.xiaoying.server.publish.entity.FileInfo;
import com.xiaoying.server.publish.entity.UploadResult;
import com.xiaoying.server.publish.upload.UploadFile;

public class UploadDealTask implements Runnable {
	private static Log log = LogFactory.getFactory().getInstance(UploadDealTask.class);
	
	private BlockingQueue<FileInfo> fileUploadQueue;
	private BlockingQueue<UploadResult> uploadResultQueue;
	private UploadFile uploadFile;
	private FileInfo fileInfo;
	
	public UploadDealTask(BlockingQueue<FileInfo> fileUploadQueue,
			BlockingQueue<UploadResult> uploadResultQueue,
			UploadFile uploadFile,FileInfo fileInfo){
		this.uploadFile = uploadFile;
		this.fileInfo = fileInfo;
		this.fileUploadQueue = fileUploadQueue;
		this.uploadResultQueue = uploadResultQueue;
	}
	
	
	@Override
	public void run() {
		UploadResult uploadResult = uploadFile.upload(fileInfo);
		// 上传次数增加1
		fileInfo.setUploadCount(fileInfo.getUploadCount()+1);
		try {
			if(uploadResult.getResultType()==UploadResult.TYPE_FAIL){
				
				int maxCount = this.getMaxUploadCount(fileInfo.getFileType());
				if(fileInfo.getUploadCount()<=maxCount){
					// 上传失败,次数小于最大上传次数,放入队列末尾重新上传
					fileInfo.setUploadCount(fileInfo.getUploadCount()+1);
					uploadResult.setResultType(UploadResult.TYPE_SUCCESS);
					this.fileUploadQueue.put(fileInfo);
					log.info("文件上传失败,重新上传 "+fileInfo.getUploadCount()+" ["+fileInfo.getFilePath()+"]");
				}else{
					// 上传次数太多了,设置错误Type=count_exceed,加入result队列
					log.error("文件上传次数太多 ["+fileInfo.getFilePath()+"]");
					uploadResult.setResultType(UploadResult.TYPE_FAIL_COUNT_EXCEED);
					this.uploadResultQueue.add(uploadResult);
				}
			}else{
				// 上传成功
				this.uploadResultQueue.add(uploadResult);
			}
		} catch (InterruptedException e) {
			log.error("重传文件放入队列失败 ["+uploadResult.getRemotePath()+"] "+e);
		}
	}
	
	/**
	 * 获取文件上传最大次数
	 * @param fileType
	 * @return
	 */
	private int getMaxUploadCount(int fileType){
		return fileType==UpYunUtil.FILETYPE_VIDEO?
				UpYunUtil.MAX_VIDEO_UPLOAD_COUNT:UpYunUtil.MAX_IMAGE_UPLOAD_COUNT;
	}

}
